<script setup lang="ts" name="CameraVideo">
import dayjs from 'dayjs';
// import { TimeLineCom } from '/@/components/TimeLine/index';
import CommonVideoPlayer, { VideoType } from '/@/libs/player/CommonVideoPlayer';
import VideoAbstract from '/@/libs/player/VideoAbstract';
import { useMessage } from '/@/hooks/message';
import { fileUpload } from '/@/api/common';
import other from '/@/utils/other';

const props = withDefaults(
	defineProps<{
		isInit?: boolean;
		type?: VideoType;
		date?: string[];
		url?: string;
	}>(),
	{
		type: VideoType.dhhls,
		url: '',
		isInit: true,
		date: () => [dayjs().startOf('date').format('YYYY-MM-DD HH:mm:ss'), dayjs().endOf('date').format('YYYY-MM-DD HH:mm:ss')],
	}
);

const emits = defineEmits<{
	onCapture: [src: string];
}>();

defineExpose({
	init,
	unLoad,
});

let canvas: any;
let ctx: any;
onMounted(() => {
	canvas = document.createElement('canvas');
	ctx = canvas.getContext('2d');

	if (props.isInit) init();
});

onUnmounted(() => {
	unLoad();
});

let videoPlayer: VideoAbstract | undefined;
let videoElement: any;
const videoLoading = ref(false);
const videoIsPlaying = ref(false);
const fastTime = 10; // 快进快退时间
const videoTotalTime = ref(0);
function init() {
	if (!props.url) {
		throw new Error('url is required');
	}

	// 每次初始化先销毁
	unLoad();

	if (!CommonVideoPlayer.isSupported(props.type)) {
		throw new Error(`${props.type} not supported`);
	}

	videoLoading.value = true;

	// 绑定元素
	videoElement = document.getElementById('trajectoryVideoElement');

	videoPlayer = CommonVideoPlayer.getInstance(props.type, {
		url: props.url,
		el: videoElement,
	});

	if (!videoPlayer) return;

	// 获取视频元素
	videoPlayer.bindVideo(videoElement);

	// 资源解析事件监听
	videoPlayer.onLoaded(() => {
		// 重新渲染时间轴
		// reRenderTimeLine();
		videoLoading.value = false;
		videoTotalTime.value = videoElement?.duration || 0;
	});

	videoPlayer.onPlaying(() => {
		sliderValue.value = videoElement?.currentTime || 0;
	});

	// 播放完成
	videoPlayer.onPlayEnd(() => {
		pause();
	});

	// 错误监听
	videoPlayer.onError(() => {
		useMessage().error('视频加载失败');
		pause();
	});
}

// 播放
function play() {
	if (!videoPlayer) return;
	videoElement.play();
	videoIsPlaying.value = true;
}

// 暂停
function pause() {
	if (!videoPlayer) return;
	videoElement.pause();
	videoIsPlaying.value = false;
}

// 快进
function fastForward() {
	if (!videoPlayer) return;
	videoElement.currentTime += fastTime;
}

// 快退
function fastBack() {
	if (!videoPlayer) return;
	videoElement.currentTime -= fastTime;
}

// 卸载
function unLoad() {
	if (videoPlayer) {
		videoPlayer.destroy();
		videoPlayer = undefined;
	}
	if (videoElement) videoElement = null;
	videoIsPlaying.value = false;
	console.log('视频回放销毁');
	const hlsWarnningTiptrajectoryVideoElement = document.querySelector('#hlsWarnningTiptrajectoryVideoElement');
	if (hlsWarnningTiptrajectoryVideoElement) hlsWarnningTiptrajectoryVideoElement.remove();
}

// 截图保存
const captureLoading = ref(false);
async function capture() {
	try {
		captureLoading.value = true;
		canvas.width = videoElement.videoWidth;
		canvas.height = videoElement.videoHeight;
		ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
		const src = canvas.toDataURL('image/png');
		const formData = new FormData();
		formData.append('file', other.base64toFile(src), 'capture.jpeg');
		const rsp = await fileUpload(formData);
		if (!rsp.data) return;

		emits('onCapture', rsp.data.ossUrl);
	} catch (err) {
		useMessage().wraning('截图失败');
	} finally {
		captureLoading.value = false;
	}
}

const sliderValue = ref(0);
function formatTooltip(value: number) {
	if (videoTotalTime.value === 0) return '0%';
	return Math.ceil((value / videoTotalTime.value) * 100) + '%';
}

function sliderChange() {
	if (!videoPlayer) return;

	videoElement.currentTime = sliderValue.value;
}

/* ----------------------- 时间轴 ------------------------- */
// const TimeLineComRef = shallowRef<InstanceType<typeof TimeLineCom>>();
// // 格式化时间轴上显示的时间
// const formatTime = (time: dayjs.Dayjs) => {
// 	// 下一天的00:00显示24:00
// 	if (time.isAfter(dayjs().format('YYYY-MM-DD 23:59:59'))) {
// 		return '24:00';
// 	}
// 	if (time.hour() === 0 && time.minute() === 0 && time.millisecond() === 0) {
// 		return time.format('HH:mm');
// 	}
// };

// function customShowTime(date: Date, zoomIndex: number) {
// 	// 当zoomIndex等于11，也就是等于我们开展的zoom时才自己处理
// 	if (zoomIndex === 11) {
// 		// 时间是2的倍数时才会显示
// 		return date.getHours() % 2 === 0 && date.getMinutes() === 0;
// 	}

// 	return false;
// }

// function reRenderTimeLine() {
// 	TimeLineComRef.value?.reRender();
// }

// const click_timeSegments = (_: any[], time: string) => {
// 	console.log(time);
// };
</script>

<template>
	<div v-loading="videoLoading" class="hls-video w-full h-full flex flex-col">
		<div class="bg-[#F3F3F3] mb-3 flex-1">
			<video id="trajectoryVideoElement" muted />
		</div>

		<div class="controls flex-s flex items-center justify-center relative">
			<img src="./icon/pre-fast.png" @click="fastBack" />
			<img v-show="videoIsPlaying" class="mx-3" src="./icon/pause.png" @click="pause" />
			<img v-show="!videoIsPlaying" class="mx-3" src="./icon/play.png" @click="play" />
			<img src="./icon/next-fast.png" @click="fastForward" />

			<el-button class="capture-btn absolute right-0 !text-primary !border-primary" :loading="captureLoading" @click="capture">
				<el-icon class="mr-2"><CameraFilled /></el-icon>
				截图保存到抓拍
			</el-button>
		</div>

		<div class="time-scale mt-7 flex flex-col px-10">
			<el-slider
				v-if="type !== VideoType.flv && type !== VideoType.dhflv"
				:disabled="videoPlayer === null"
				v-model="sliderValue"
				:max="videoTotalTime"
				:format-tooltip="formatTooltip"
				@change="sliderChange"
			/>
			<!-- <TimeLineCom
				ref="TimeLineComRef"
				:timeRange="{
					start: date[0],
					end: date[1],
				}"
				:initTime="dayjs(date[0]).add(12, 'hours').valueOf()"
				:initZoomIndex="11"
				:showCenterLine="false"
				:showDateAtZero="false"
				:enableZoom="false"
				:enableDrag="false"
				:extendZOOM="[
					{
						zoom: 25,
						zoomHourGrid: 0.5,
					},
				]"
				:timeSegments="[
					{
						beginTime: dayjs(date[0]).valueOf(), // 起始时间戳
						endTime: dayjs(date[1]).valueOf(), // 结束时间戳
						color: '#E6EFFA', // 颜色
						startRatio: 0.65, // 高度的起始比例，即top=时间轴高度*startRatio
						endRatio: 0.9, // 高度的结束比例，即bottom=时间轴高度*endRatio
					},
				]"
				:formatTime="formatTime"
				:customShowTime="customShowTime"
				@click_timeSegments="click_timeSegments"
			></TimeLineCom> -->
		</div>
	</div>
</template>

<style lang="scss" scoped>
:deep(#dhHlsVideoWrappertrajectoryVideoElement),
:deep(#trajectoryVideoElement) {
	height: 475px !important;
	width: 100% !important;
}
:deep(#dhHlsVdieoCloseBtntrajectoryVideoElement) {
	display: none;
}

:deep(.el-slider) {
	--el-slider-button-wrapper-size: 32px;
	--el-slider-button-size: 12px;
	--el-slider-height: 2px;
}
.controls {
	img {
		width: 37px;
		height: 37px;
		cursor: pointer;
	}

	:deep(.el-button.is-loading) {
		position: absolute;
	}
}

.time-scale {
	height: 53px;
}
</style>
